package com.maiji.cloud.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.maiji.cloud.config.MyRedisConfig;
import com.maiji.cloud.entities.login.AppUser;
import com.maiji.cloud.entities.login.ShareWeightRuleEntity;
import com.maiji.cloud.entities.shopingmall.*;
import com.maiji.cloud.mapper.*;
import com.maiji.cloud.microservice.UserInfoService;
import com.maiji.cloud.request.BaseDataReqDto;
import com.maiji.cloud.request.shopingmall.DistributeIntegralReqDto;
import com.maiji.cloud.request.shopingmall.UserBindWinthdrawAccountResData;
import com.maiji.cloud.response.BaseDataResDto;
import com.maiji.cloud.response.BaseResDto;
import com.maiji.cloud.response.Status;
import com.maiji.cloud.response.shopingmall.CapitalInfoResData;
import com.maiji.cloud.response.shopingmall.CapitalMainResData;
import com.maiji.cloud.response.shopingmall.FinancialDetailsResData;
import com.maiji.cloud.response.shopingmall.GetDiscountCouponListResData;
import com.maiji.cloud.service.CapitalMainLogService;
import com.maiji.cloud.service.CapitalMainService;
import com.maiji.cloud.service.CouponsService;
import com.maiji.cloud.service.RuleFundIntegralService;
import com.maiji.cloud.utils.*;

import com.sun.istack.Nullable;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;

import java.math.RoundingMode;
import java.text.NumberFormat;
import java.util.*;

@Service
@Transactional
public class CapitalMainServiceImpl extends ServiceImpl<CapitalMainMapper, CapitalMain> implements CapitalMainService {

    private Logger logger = LoggerFactory.getLogger(ShopingOrderServiceImpl.class);
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
	private MongoTemplate mongoTemplate;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private CapitalMainLogService capitalMainLogService;
    @Autowired
    private RuleFundIntegralService ruleFundIntegralService;
    @Autowired
    private CouponsService couponsService;
    @Autowired
    private CapitalMainMapper capitalMainMapper;
    @Autowired
	private DistributionLogMapper distributionLogMapper;
    @Autowired
    private CapitalIOMapper capitalIOMapper;
    @Autowired
    private CapitalMainLogMapper capitalMainLogMapper;
    @Autowired
    private TaskMapper taskMapper;
    @Autowired
	private BindWithdrawAccountMapper bindWithdrawAccountMapper;

    /**
     * 创建用户资金账户
     * @param userId
     * @return
     */
    @Override
    public Boolean createCapitalMain(String userId){
        Wrapper<CapitalMain> wrapper = new EntityWrapper<CapitalMain>()
                .eq("user_id", userId);
        CapitalMain capitalMain = selectOne(wrapper);
        if (capitalMain != null) return true;
        return insert(new CapitalMain()
                .setUserId(UUID_MD5.getUUID())
                .setUserId(userId)
                .setUpdateDate(new Date()));
    }

    @Override
    public Boolean updateCapitalMain(String userId, FlowTypeEnum capitalType, String changeQuantity, FlowTypeEnum changeType, FlowTypeEnum remark, String relevantId) {
        return (updateCapitalMainWithMainLog(userId, capitalType, changeQuantity, changeType, remark, relevantId) != null);
    }

    private CapitalMainLog  updateCapitalMainWithMainLog(String userId, FlowTypeEnum capitalType, String changeQuantity, FlowTypeEnum changeType, FlowTypeEnum remark, String relevantId){
        // 记录基金流水
        CapitalMainLog capitalMainLog = null;
        try {
            capitalMainLog = new CapitalMainLog();
            String capitalMainLogId = UUID_MD5.getUUID();
            capitalMainLog.setUuId(capitalMainLogId)
                    .setUserId(userId)
                    .setCapitalType(capitalType.getKey())
                    .setChangeQuantity(Double.valueOf(changeQuantity))
                    .setChangeType(changeType.getKey())
                    .setChangeDate(new Date())
                    .setRemark(remark.getKey())
                    .setRelevantId(relevantId);
            if (! capitalMainLogService.insert(capitalMainLog)) {
                logger.info("UserID={} ===>> 记录资金流水: capitalType={}, changeQuantity={}, changeType={}, remark={}}, relevantId={} ===>> 失败",
                        new Object[]{userId, capitalType.getValue(), changeQuantity, changeType.getValue(), remark.getValue(), relevantId});
                return null;
            }
            // 修改账户表
            CapitalMain capitalMain = selectOne(new EntityWrapper<CapitalMain>().eq("user_id", userId));
            if (capitalMain == null){
                createCapitalMain(userId);
            }
            if (changeType == FlowTypeEnum.DECREASE) changeQuantity = "-" + changeQuantity;
            if (capitalType == FlowTypeEnum.FUND) capitalMain.setFund(Arith.add(2, capitalMain.getFund(), Double.valueOf(changeQuantity)));
            if (capitalType == FlowTypeEnum.INTEGRAL) capitalMain.setIntegral(capitalMain.getIntegral() + Integer.valueOf(changeQuantity));
            if (capitalType == FlowTypeEnum.RETURNMONEY) {
                capitalMain.setMoney(Arith.add(2, capitalMain.getMoney(), Double.valueOf(changeQuantity)));
                capitalMain.setReturnMoney(Arith.add(2, capitalMain.getReturnMoney(), Double.valueOf(changeQuantity)));
            }
            if (! updateById(capitalMain.setUpdateDate(new Date()))) {
                logger.info("UserID={} ===>> 修改资金表: capitalType={}, changeQuantity={}, changeType={}, remark={} ===>> 失败",
                        new Object[]{userId, capitalType.getValue(), changeQuantity, changeType.getValue(), remark.getValue(), relevantId});
                capitalMainLogService.deleteById(capitalMainLogId);
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("UserID={} ===>> 修改资金表: capitalType={}, changeQuantity={}, changeType={}, remark={} ===>> 报错",
                    new Object[]{userId, capitalType.getValue(), changeQuantity, changeType.getValue(), remark.getValue(), relevantId});
        }
        logger.info("UserID={} ===>> 修改资金表: capitalType={}, changeQuantity={}, changeType={}, remark={} ===>> 成功",
                new Object[]{userId, capitalType.getValue(), changeQuantity, changeType.getValue(), remark.getValue(), relevantId});
        return capitalMainLog;
    }

    @Override
    public BaseDataResDto<FinancialDetailsResData> distributeIntegralByRemarkInt(DistributeIntegralReqDto distributeIntegralReqDto,String maijiToken){
        BaseDataResDto<FinancialDetailsResData> baseDataResDto = new BaseDataResDto();
        try{
            Integer integral = distributeIntegralReqDto.getData().getIntegral();
            if(integral == null){
                TaskEntity task = new TaskEntity();
                task.setType(distributeIntegralReqDto.getData().getRemark().getKey());
                task = taskMapper.selectOne(task);
                integral = task.getIntegral();
            }
            FlowTypeEnum remark = distributeIntegralReqDto.getData().getRemark();
            String relevantId = distributeIntegralReqDto.getData().getRelevantId();
            if (integral != null && integral.intValue() != 0 && remark != null){
                AppUser appUser = RedisUtil.getAppUserByRedis(redisTemplate, MyRedisConfig.REDISDATABASENO, maijiToken, userInfoService);
                CapitalMainLog mainLog = updateCapitalMainWithMainLog(appUser.getUuId(), FlowTypeEnum.INTEGRAL, integral.toString(), FlowTypeEnum.INCREASE, remark, relevantId);
                if(mainLog != null){
                    FinancialDetailsResData financialDetails = new FinancialDetailsResData();
                    BeanUtils.copyProperties(mainLog,financialDetails);
                    financialDetails.setRemarkInt(remark.getKey());
                    baseDataResDto.setData(financialDetails);
                }
            }
        }catch (Exception exc){
            baseDataResDto.setStatus(Status.ERROR);
            baseDataResDto.setMessage(exc.getMessage());
        }
        return baseDataResDto;
    }

    @Override
    public CapitalMainResData calculateCapitalMain(String userId, Double presentPayable, String token) {
        // 获取用户账户信息
        CapitalMainResData capitalMainResData = new CapitalMainResData();
        EntityWrapper<CapitalMain> capitalMainWrapper = new EntityWrapper<>();
        capitalMainWrapper.eq("user_id", userId);
        CapitalMain capitalMain = selectOne(capitalMainWrapper);
        if (capitalMain == null) createCapitalMain(userId);

        // 计算用户余额是否可用
        capitalMainResData.setMoney(capitalMain.getReturnMoney());
        if (capitalMain.getReturnMoney() >= presentPayable) capitalMainResData.setMoneyUsable(true);

        // 计算用户减肥基金是否可用
        EntityWrapper<RuleFundIntegral> ruleFundWrapper = new EntityWrapper<>();
        ruleFundWrapper.eq("type", 1)
                .le("purchase_amount", presentPayable)
                .orderBy("purchase_amount", false);
        RuleFundIntegral ruleFund = ruleFundIntegralService.selectOne(ruleFundWrapper);
        if (ruleFund != null) {
            capitalMainResData.setFundUsable(true);
            Double discountAmount = Arith.multiplys(2, presentPayable, Arith.divides(2, ruleFund.getDiscountRatio(), 100));
            if (discountAmount < capitalMain.getFund()) capitalMainResData.setFund(discountAmount);
            else {
                if (capitalMain.getFund() == 0) capitalMainResData.setFundUsable(false);
                capitalMainResData.setFund(capitalMain.getFund());
            }
        }

        // 计算用户积分是否可用
        EntityWrapper<RuleFundIntegral> ruleIntegralWrapper = new EntityWrapper<>();
        ruleIntegralWrapper.eq("type", 2)
                .le("purchase_amount", presentPayable)
                .orderBy("purchase_amount", false);
        RuleFundIntegral ruleIntegral = ruleFundIntegralService.selectOne(ruleIntegralWrapper);
        if (ruleIntegral != null) {
            capitalMainResData.setIntegralUsable(true);
            Double discountAmount = Arith.multiplys(2, presentPayable, Arith.divides(2, ruleFund.getDiscountRatio(), 100));
            Integer toMoneyRatio = ruleIntegral.getToMoneyRatio();
            // 积分兑换减免金额所需积分值
            Integer integral = (int) Arith.multiplys(2, Arith.divides(2, discountAmount, toMoneyRatio), 1000);
            Integer capitalMainIntegral = capitalMain.getIntegral();
            if (integral < capitalMainIntegral) capitalMainResData.setIntegral(integral).setIntegralMoney(discountAmount);
            else {
                discountAmount = Arith.divides(2, Arith.multiplys(2, capitalMainIntegral, toMoneyRatio), 1000);
                capitalMainResData.setIntegral(capitalMainIntegral).setIntegralMoney(discountAmount);
            }
        }

        // 计算用户是否有可用的优惠券
        List<GetDiscountCouponListResData> coponUseable = couponsService.getUsableDiscountCouponList(presentPayable, token).getData();
        List<GetDiscountCouponListResData> couponNo = couponsService.noPossessDiscountCouponList(presentPayable, token).getData();
        coponUseable.addAll(couponNo);
        capitalMainResData.setCouponList(coponUseable);

        return capitalMainResData;
    }

	@Override
	public BaseDataResDto<CapitalInfoResData> getCapitalInfo(String maijiToken) {
		logger.info("CapitalMainServiceImpl.getCapitalInfo ,maijiToken is {}",maijiToken);
		// 获得用户id
		AppUser appUser = RedisUtil.getAppUserByRedis(redisTemplate, MyRedisConfig.REDISDATABASENO, maijiToken, userInfoService);
		if (appUser == null) {
			logger.info("CapitalMainServiceImpl.getCapitalInfo ,appUser is {}",
					JSON.toJSONString(appUser));
			return new BaseDataResDto(Status.ERROR,"token无效");
		}
		
		CapitalMain capitalMain = capitalMainMapper.selectOneByUserId(appUser.getUuId());
        if (capitalMain == null){
            createCapitalMain(appUser.getUuId());
        }
		CapitalInfoResData capitalInfoResData = new CapitalInfoResData();
		
		if(capitalMain != null ) {
			BeanUtils.copyProperties(capitalMain, capitalInfoResData);
		}
		//获得总获得减肥基金
		Double sumHavefund = capitalMainLogMapper.sumMoney(CommonIntValueEnum.CAPITAL_TYPE_fund.getValue(), appUser.getUuId(), CommonIntValueEnum.CHANGE_TYPPE_ADD.getValue(),null);
		//获得总消费减肥基金
		Double sumConsumefund = capitalMainLogMapper.sumMoney(CommonIntValueEnum.CAPITAL_TYPE_fund.getValue(), appUser.getUuId(), CommonIntValueEnum.CHANGE_TYPPE_REDUCE.getValue(),null);
		
		//获得总获得积分
		Double sumHaveIntegral = capitalMainLogMapper.sumMoney(CommonIntValueEnum.CAPITAL_TYPE_INTEGRAL.getValue(), appUser.getUuId(), CommonIntValueEnum.CHANGE_TYPPE_ADD.getValue(),null);
	
		//获得总消费积分
		Double sumConsumeIntegral = capitalMainLogMapper.sumMoney(CommonIntValueEnum.CAPITAL_TYPE_INTEGRAL.getValue(), appUser.getUuId(), CommonIntValueEnum.CHANGE_TYPPE_REDUCE.getValue(),null);
		
		capitalInfoResData.setSumHaveFund(sumHavefund);
		capitalInfoResData.setSumConsumeFund(sumConsumefund);
		
		capitalInfoResData.setSumHaveIntegral(sumHaveIntegral);
		capitalInfoResData.setSumConsumeIntegral(sumConsumeIntegral);
		
		//获取已经提现的分销基金
		Double distributionWithdraw = capitalIOMapper.selectWithdrawSum(appUser.getUuId(), CommonIntValueEnum.CAPITAL_TYPE_OUT.getValue(), CommonIntValueEnum.WITHDRAWDISTRIBUTION.getValue()+"");
		capitalInfoResData.setDistributionWithdraw(distributionWithdraw);
		
		//获取已经提现的订单返现资金
		Double balanceWithdrawSum = capitalIOMapper.selectWithdrawSum(appUser.getUuId(), CommonIntValueEnum.CAPITAL_TYPE_OUT.getValue(), CommonIntValueEnum.WITHDRAWORDERRETURN.getValue()+"");
		capitalInfoResData .setBalanceWithdrawSum(Arith.add(2, balanceWithdrawSum == null? 0.0  : balanceWithdrawSum,distributionWithdraw == null? 0.0  : distributionWithdraw));
		List<Integer> remarksBalanceConsume =  new ArrayList<Integer>();
		remarksBalanceConsume.add(FlowTypeEnum.BALANCE_PAY.getKey());
		// 获得订单返现余额消费总额
		Double sumBalanceConsumeOne = capitalMainLogMapper.sumMoney(CommonIntValueEnum.CAPITAL_TYPE_MONEY.getValue(),
				appUser.getUuId(), CommonIntValueEnum.CHANGE_TYPPE_REDUCE.getValue(),remarksBalanceConsume);
	
		// 获得分销余额消费总额
		Double sumBalanceConsumeTwo = capitalMainLogMapper.sumMoney(CommonIntValueEnum.CAPITAL_TYPE_DISTRIBUTION.getValue(),
				appUser.getUuId(), CommonIntValueEnum.CHANGE_TYPPE_REDUCE.getValue(),remarksBalanceConsume);
		Double balanceConsumeSum = Arith.add(2, sumBalanceConsumeOne == null ? 0.0:sumBalanceConsumeOne,sumBalanceConsumeTwo == null ? 0.0:sumBalanceConsumeTwo);
		capitalInfoResData.setBalanceConsumeSum(balanceConsumeSum);
		
		List<Integer> remarksOrderReturnMoney =  new ArrayList<Integer>();
		remarksOrderReturnMoney.add(FlowTypeEnum.SHAREORDERHELP.getKey());
		
		//获得订单返现总额
		Double orderReturnMoney = capitalMainLogMapper.sumMoney(CommonIntValueEnum.CAPITAL_TYPE_MONEY.getValue(),
				appUser.getUuId(), CommonIntValueEnum.CHANGE_TYPPE_ADD.getValue(),remarksOrderReturnMoney);
		capitalInfoResData.setOrderReturnMoney(orderReturnMoney == null ? 0.0 : orderReturnMoney);
		
		BaseDataResDto<CapitalInfoResData> reponseData = new BaseDataResDto<CapitalInfoResData>(Status.SUCCESS);
		reponseData.setData(capitalInfoResData);
		
		return reponseData;
	}

	@Override
	@Transactional(isolation = Isolation.READ_UNCOMMITTED)
	public Boolean unfreezeDistributionMoney(String orderId) {
		logger.info("CapitalMainServiceImpl.unfreezeDistributionMoney ,orderId is {}",orderId);
		//根据订单id查询产生的分销资金记录
		if(StringUtils.isBlank(orderId)) return false; 
		DistributionLogEntity distributionLogEntity = distributionLogMapper.getDistributionLogByOrderId(orderId, CommonIntValueEnum.DISTRIBUTION_LOG_LEVEL_ONE.getValue());
		if(distributionLogEntity != null) {
			//解冻上级用户资金
			CapitalMain capitalMain = capitalMainMapper.selectOneByUserId(distributionLogEntity.getUserId());
			capitalMain.setFrozenCapital(Arith.subtract(2, capitalMain.getFrozenCapital(),distributionLogEntity.getMoney()));
			capitalMain.setDistributionMoney(Arith.add(2, capitalMain.getDistributionMoney(),distributionLogEntity.getMoney()));
			if(capitalMainMapper.updateById(capitalMain) <= 0) {
				unfreezeDistributionMoney(orderId);
			}
			//记录流水
			CapitalMainLog capitalMainLog = new CapitalMainLog();
			capitalMainLog.setUuId(UUID_MD5.getUUID());
			capitalMainLog.setCapitalType(CommonIntValueEnum.CAPITAL_TYPE_DISTRIBUTION.getValue());
			capitalMainLog.setUserId(distributionLogEntity.getUserId());
			capitalMainLog.setChangeQuantity(distributionLogEntity.getMoney());
			capitalMainLog.setChangeType(CommonIntValueEnum.CHANGE_TYPPE_ADD.getValue());
			capitalMainLog.setChangeDate(new Date());
			capitalMainLog.setRemark(FlowTypeEnum.UNFREEZE.getKey());
			capitalMainLog.setRelevantId(distributionLogEntity.getUuId());
			capitalMainLogService.insert(capitalMainLog);
			
		}
		//解冻上上级用户的资金
		DistributionLogEntity distributionLogEntityTwo = distributionLogMapper.getDistributionLogByOrderId(orderId, CommonIntValueEnum.DISTRIBUTION_LOG_LEVEL_TWO.getValue());
		if(distributionLogEntityTwo != null) {
			//解冻上级用户资金
			CapitalMain capitalMain = capitalMainMapper.selectOneByUserId(distributionLogEntityTwo.getUserId());
			capitalMain.setFrozenCapital(Arith.subtract(2, capitalMain.getFrozenCapital(),distributionLogEntityTwo.getMoney()));
			capitalMain.setDistributionMoney(Arith.add(2, capitalMain.getDistributionMoney(),distributionLogEntityTwo.getMoney()));
			if(capitalMainMapper.updateById(capitalMain) <= 0) {
				unfreezeDistributionMoney(orderId);
			}
			//记录流水
			CapitalMainLog capitalMainLog = new CapitalMainLog();
			capitalMainLog.setUuId(UUID_MD5.getUUID());
			capitalMainLog.setCapitalType(CommonIntValueEnum.CAPITAL_TYPE_MONEY.getValue());
			capitalMainLog.setUserId(distributionLogEntityTwo.getUserId());
			capitalMainLog.setChangeQuantity(distributionLogEntityTwo.getMoney());
			capitalMainLog.setChangeType(CommonIntValueEnum.CHANGE_TYPPE_ADD.getValue());
			capitalMainLog.setChangeDate(new Date());
			capitalMainLog.setRemark(FlowTypeEnum.UNFREEZE.getKey());
			capitalMainLog.setRelevantId(distributionLogEntityTwo.getUuId());
			capitalMainLogService.insert(capitalMainLog);
		}
		return true;
	}

	@Override
	public BaseResDto userBindWinthdrawAccount(BaseDataReqDto<UserBindWinthdrawAccountResData> param, String maijiToken) {
		logger.info("CapitalMainServiceImpl.userBindWinthdrawAccount ,param is {},maijiToken is {}",maijiToken,JSON.toJSONString(param));
		// 获得用户id
		AppUser appUser = RedisUtil.getAppUserByRedis(redisTemplate, MyRedisConfig.REDISDATABASENO, maijiToken, userInfoService);
		if (appUser == null) {
			logger.info("CapitalMainServiceImpl.getCapitalInfo ,appUser is {}",
					JSON.toJSONString(appUser));
			return new BaseResDto(Status.ERROR,"token无效");
		}
		
		BindWithdrawAccountEntity entity = new BindWithdrawAccountEntity();
		entity.setUserId(appUser.getUuId());
		entity.setType(param.getData().getType());
		BindWithdrawAccountEntity  bindWithdrawAccountEntity = bindWithdrawAccountMapper.selectOne(entity );
		
		if(bindWithdrawAccountEntity != null)return new BaseResDto(Status.PARAMETERERROR,"账号已经绑定,不可重复绑定");
		
//		if(param.getData().getType() == CommonIntValueEnum.BIND_WITHDRAW_ACCOUNT_TYPE_ALIPAY.getValue() && !appUser.getTel().equals(param.getData().getAccount())) 
//			return new BaseResDto(Status.ERROR,"支付宝账号与绑定的手机号不一至");
//			
//		if(param.getData().getType() == CommonIntValueEnum.BIND_WITHDRAW_ACCOUNT_TYPE_WX.getValue() && !appUser.getTel().equals(param.getData().getTel())) 
//			return new BaseResDto(Status.ERROR,"微信账号与绑定的手机号不一至");
		
		
		bindWithdrawAccountEntity = new BindWithdrawAccountEntity();
		
		BeanUtils.copyProperties(param.getData(), bindWithdrawAccountEntity);
		bindWithdrawAccountEntity.setInTime(new Date());
		bindWithdrawAccountEntity.setUuId(UUID_MD5.getUUID());
		bindWithdrawAccountEntity.setUserId(appUser.getUuId());
		bindWithdrawAccountMapper.insert(bindWithdrawAccountEntity);
		
		return new BaseResDto(Status.SUCCESS);
	}

    @Override
    public List<CapitalMain> findAllCapitalMains(List<String> userIds) {
        EntityWrapper<CapitalMain> entityWrapper = new EntityWrapper<>();
        entityWrapper.in("user_id", userIds);
        return selectList(entityWrapper);
    }

    @Override
    public BaseDataResDto<Map<String, Object>> findCapitalMainCount () {
        EntityWrapper<CapitalMain> entityWrapper = new EntityWrapper<>();
        entityWrapper.setSqlSelect("sum(money) money, sum(return_money) returnMoney, sum(frozen_capital) frozen," +
                "sum(distribution_Money) distribution, sum(fund) fund, sum(integral) integral");
        Map<String, Object> map = selectMap(entityWrapper);
        return new BaseDataResDto<Map<String, Object>>(Status.SUCCESS).setData(map);
    }

	@Override
	public BaseResDto editWithdrawalAmountLimitConfig(WithdrawalAmountLimitConfigEntity withdrawalAmountLimitConfig) {
        Query query = new Query(Criteria.where("type").is(1));
        mongoTemplate.findAndRemove(query, WithdrawalAmountLimitConfigEntity.class, WithdrawalAmountLimitConfigEntity.TABLE_NAME);
        mongoTemplate.save(withdrawalAmountLimitConfig, WithdrawalAmountLimitConfigEntity.TABLE_NAME);
        mongoTemplate.save(withdrawalAmountLimitConfig, WithdrawalAmountLimitConfigEntity.TABLE_LOG_NAME);
		return new BaseResDto(Status.SUCCESS);
	}

	@Override
	public BaseDataResDto<WithdrawalAmountLimitConfigEntity> findWithdrawalAmountLimitConfig(Integer type) {
		// 获取分销账户最低提现金额
        WithdrawalAmountLimitConfigEntity withdrawalAmountLimitConfigEntity = mongoTemplate.findOne(
                new Query(Criteria.where("type").is(type)), WithdrawalAmountLimitConfigEntity.class, WithdrawalAmountLimitConfigEntity.TABLE_NAME);
		return new BaseDataResDto<WithdrawalAmountLimitConfigEntity>(Status.SUCCESS).setData(withdrawalAmountLimitConfigEntity);
	}

    @Override
    public BaseDataResDto<List<WithdrawalAmountLimitConfigEntity>> findAllWithdrawalAmountLimitConfigLogs(List<Date> updateDates) {
        Query query = new Query(Criteria.where("type").is(1));
        query.skip(1).with(new Sort(new Sort.Order(Sort.Direction.DESC,"updateDate")));
        Date startDate = updateDates.size() > 0 ? updateDates.get(0): null;
        Criteria updateDateCriteria = Criteria.where("updateDate");
        Boolean updFlag = false;
        if (startDate != null) {
            updateDateCriteria = updateDateCriteria.gte(startDate);
            updFlag = true;
        }
        Date endDate = updateDates.size() > 1 ? updateDates.get(1): null;
        if (endDate != null) {
            updateDateCriteria = updateDateCriteria.lte(endDate);
            updFlag = true;
        }
        if (updFlag) query.addCriteria(updateDateCriteria);
        if (startDate == null && endDate == null) query.limit(1);
        List<WithdrawalAmountLimitConfigEntity> withdrawalAmountLimitConfigs = mongoTemplate.find(query,
                WithdrawalAmountLimitConfigEntity.class, WithdrawalAmountLimitConfigEntity.TABLE_LOG_NAME);
        return new BaseDataResDto<List<WithdrawalAmountLimitConfigEntity>>(Status.SUCCESS).setData(withdrawalAmountLimitConfigs);
    }

}
